<?php
class mainController extends AController {
	public function indexAction() {
		$this->mode = $this->request->getGetParameter('demo');
		if(!isset($_SESSION['user']) || empty($_SESSION['user']['username'])){
			return $this->render('main/login.php');
		}else{
			return $this->render();
		}
	}
	
	public function loginAction(){
			if(isset($_POST['sub_login'])){
				$username = $this->request->getPostParameter('login_name');
				$pwd = $this->request->getPostParameter('login_pwd');
				if(empty($username) && empty($pwd)){
					$this->msg = '用户名和密码不能为空';
				}else{
					if($this->checkUser($username,$pwd)){
						$userinfo = $this->getUserInfoByName($username);
						$this->setUserLoginSession($userinfo);
						if($userinfo['UNIT_ID']>0){
							$this->getHiddenMenus();
						}
						$mode = $this->request->getGetParameter('demo');
						if($mode){
							return $this->redirect('/?c=demo');
						}else{
							return $this->redirect('/');
						}
					}else{
						$this->msg = '用户名或密码不正确';
					}
				}
			}
			return $this->render();
	}
	
	function logoutAction(){
		session_destroy();
		if(empty($_REQUEST['demo'])){
			$this->redirect('/');
		}else{
			$this->redirect('/?demo=1');
		}
	}
	
	function checkUser($username,$pwd){
		$flag = JYDB::find('SYSUSER','user_name=\''.$username.'\' and password=\''.md5($pwd).'\'','count(*) num');
		$flag = $flag['NUM'];
		return $flag; 
	}
	function getUserInfoByName($name){
		return JYDB::find('SYSUSER','user_name=\''.$name.'\'');
	}
	function setUserLoginSession($user){
		$_SESSION['user']['user_id'] = $user['USER_ID'];
		$_SESSION['user']['username'] = $user['USER_NAME'];
		$_SESSION['user']['truename'] = $user['TRUE_NAME'];
		$_SESSION['user']['doc_no'] = $user['DOC_NO'];
		$_SESSION['user']['unit_id'] = $user['UNIT_ID'];
		$_SESSION['user']['role_id'] = $user['ROLE_ID'];
		$_SESSION['user']['work_no'] = $user['WORK_NO'];
		$_SESSION['monthaccess'] = JYVisit::getMonthVisit($user['USER_ID']);
		$_SESSION['dayaccess'] = JYVisit::getTodayVisit($user['USER_ID']);
	}
	function getHiddenMenus(){
		$menus =  ATools::getConfig('menu');
		$ROLE_ID = $_SESSION['user']['role_id'];
		if ($ROLE_ID) {
			$where = "ROLE_ID=$ROLE_ID";
			$role_meuns = JYDB::find("ROLE",$where,"*","");
		}
		foreach ($menus as $v){
			$flag = false;
			foreach ($v['menus'] as $k=>$val){
				if(strpos($role_meuns['MENUS'],$k)!==false){
					$flag |= true;
				}
			}
			
			if(!$flag){
				$hiddens[] = $v['code'];
			}
		}
		unset($menus);
		if(count($hiddens)>0){
			$_SESSION['menus']['hidden'] = implode(',',$hiddens);
		}else{
			$_SESSION['menus']['hidden'] = '';
		}
		return $hiddens;
	}
}